package parser;

import java.util.ArrayList;
import java.util.ListIterator;

/**
 * LogoScope is passed through the program when checking that identifiers are
 * used only when it is legal to use them.
 */
public class LogoScope {
	public ArrayList<LogoIdentifier> identifiers;

	public LogoScope() {
		identifiers = new ArrayList<LogoIdentifier>();
	}

	/**
	 * Adds an identifier to the array of identifiers which are legal in the
	 * current context
	 * 
	 * @param identifier
	 * @return false if the identifier is already in the list. True if it is
	 *         added successfully.
	 */
	public boolean pushIdentifier(LogoIdentifier identifier) {
		for (LogoIdentifier ident : identifiers) {
			if (ident.identifier.equals(identifier.identifier)) {
				return false;
			}
		}
		identifiers.add(identifier);
		return true;
	}

	/**
	 * Removes the specified identifier from the list. Used when checking
	 * procedures, you must add the argument before checking the statements for
	 * correct use of identifiers. Then remove it before checking another
	 * procedure
	 * 
	 * @param identifier
	 */
	public void popIdentifier(LogoIdentifier identifier) {
		ListIterator<LogoIdentifier> it = identifiers.listIterator();
		while (it.hasNext()) {
			LogoIdentifier ident = it.next();
			if (ident.identifier.equals(identifier.identifier)) {
				it.remove();
			}
		}
	}

	/**
	 * Gets the IdentifierType for the specified Identifier Also implicityly
	 * tells you if an identifier exists
	 * 
	 * @param identifier
	 * @return
	 */
	public LogoIdentifierType getTypeOf(String identifier) {
		for (LogoIdentifier ident : identifiers) {
			if (ident.identifier.equals(identifier)) {
				return ident.type;
			}
		}
		return null;
	}
}
